<template>
  <!-- 面包屑导航 -->
  <div className="break">
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>食堂管理</el-breadcrumb-item>
      <el-breadcrumb-item><b>菜品管理</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <!-- 搜索工具栏-->
  <div style="margin:40px 20px 20px 20px">
    <el-form :inline="true" ref="searchFormRef" :model="searchFormModel" class="demo-form-inline" style="margin-top: 20px">
      <el-form-item label="菜品" prop="dname">
        <el-input v-model="searchFormModel.dname" placeholder="请输入菜品" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="searchOnSubmit">查询</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!--  数据表格-->
  <div style="margin:20px">
    <el-table :data="blogInfo" stripe border style="width: 100%"
    >
      <el-table-column v-if="showMidColumn" prop="did" label="序号" width="55px" >
        <template #default="{ row }">
          <!-- 根据状态改变文本颜色 -->
          <span :class="statusClass(row.did)">
              {{ row.did }}
            </span>
        </template>
      </el-table-column>
      <el-table-column prop="mname" label="店铺" />
      <el-table-column prop="dname" label="菜品" />
      <el-table-column prop="dphotourl" label="图片" width="120px">
        <template #default="{ row }">
          <el-image
              style="width: 100px; height: 100px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2)"
              :src="'http://localhost:8085' + row.dphotourl"
              :alt="'菜品图片 - '+row.dname"
              fit="cover"
              :preview-src-list="['http://localhost:8085' + row.dphotourl]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="dprice" label="价格" />
      <el-table-column prop="dfood" label="主要食材" />
      <el-table-column prop="isdel" label="状态" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button
              size="small"
              :type="scope.row.status === 1 ? 'success' : 'primary'"
              @click="toggleLockHandler(scope.row)">
            <template v-if="scope.row.status === 1">
              <el-icon><Lock /></el-icon>
            </template>
            <template v-else>
              <el-icon><Unlock /></el-icon>
            </template>
            {{ scope.row.status === 1 ? '' : '' }}
          </el-button>
          <el-button size="small" @click="tableEditHandler(scope.$index, scope.row)">
            <el-icon><Edit /></el-icon>
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="tableDeleteHandler(scope.$index, scope.row)">
            <el-icon><Delete /></el-icon>
          </el-button>
        </template>
      </el-table-column>
<!--      <el-table-column label="审核" width="160">
        <template #default="{ row }">
          &lt;!&ndash; 操作按钮 &ndash;&gt;
          <el-button
              type="success"
              size="default"
              :disabled="approveDisabledMap[row.did]"
              @click="approveAudit(row)"
          >
            <el-icon><CircleCheck /></el-icon>
          </el-button>
          <el-button
              type="danger"
              size="default"
              :disabled="rejectDisabledMap[row.did]"
              @click="rejectAudit(row)"
          >
            <el-icon><CircleClose /></el-icon>
          </el-button>
        </template>
      </el-table-column>-->
    </el-table>
  </div>
  <!--  分页-->
  <div class="page" style="width: 50%;margin: 0 auto;padding-left: 230px">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3,4]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!--   编辑模态框-->
  <el-dialog v-model="dialogEditState" title="修改菜品价格" width="380">
    <div>
      <el-form ref="formEditRef" :model="formEdit" label-width="120px">
        <el-form-item prop="dname" label="菜品">
          <el-input v-model="formEdit.dname" disabled></el-input>
        </el-form-item>
        <el-form-item prop="dtype" label="菜品类型">
            <el-input v-model="formEdit.dtype" disabled></el-input>
        </el-form-item>
        <el-form-item prop="dprice" label="菜品价格">
          <el-input v-model="formEdit.dprice" ></el-input>
        </el-form-item>
        <el-form-item prop="dphotourl" label="菜品照片">
          <el-input v-model="formEdit.dphotourl" disabled></el-input>
        </el-form-item>
        <el-form-item prop="dfood" label="主要食材" style="display: none;">
          <el-input v-model="formEdit.dfood"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogEditOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogEditOnSubmit" >确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {Unlock,Lock,Delete,Edit,CircleCheck,CircleClose} from "@element-plus/icons";
import {onMounted, reactive, ref} from "vue";
import request from "@/utils/canteen";
import {ElMessage, ElMessageBox} from "element-plus";
import {ArrowRight} from "@element-plus/icons-vue";
onMounted(()=>{
  info();
  getDish();
})

//分页
const currentPage = ref(1)
const pageSize = ref(4)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let totals=ref(0);
const  blogInfo=ref([])

const userInfo=reactive({
  'mid':'',
})
const mallidvalue = ref([])
const info = async () => {
  // 从 sessionStorage 取出数据
  const loginUser = sessionStorage.getItem("loginUser");
  if (loginUser) {
    // 更新 userInfo.username
    const userobj = JSON.parse(loginUser)
    userInfo.mid = userobj.mid;
    console.log(userInfo.mid)
    formAdd.mallid = userInfo.mid;  // 直接在这里设置 formAdd 的 mallid 值
  }
}

// 表格显示内容
const getDish = () => {
  const params={
    pageNum: currentPage.value,
    pageSize: pageSize.value,
  };
  // 模糊查询
  if (searchFormModel.dname && searchFormModel.dname.trim() !== '') {
    params.dname = searchFormModel.dname.trim();
  }
  request({
    url: '/dishes/foods1',
    method: 'get',
    params,
  }).then((req) => {
    console.log(req)
    if (200 == req.data.errorCode) {
      blogInfo.value = req.data.data.records.map(item => ({
        ...item,
        isLocked: item.status === 0 // 根据数据库中的status值设置isLocked
      }));
      totals.value = req.data.data.total;
      blogInfo.value.forEach((item) => {
        if(item.isdel == "已同意"){
          approveDisabledMap[item.did] = true;
          rejectDisabledMap[item.did] = true;
        }else if (item.isdel == "已拒绝") {
          approveDisabledMap[item.did] = true;
          rejectDisabledMap[item.did] = true;
        }else if(item.isdel == "未审核"){
          approveDisabledMap[item.did] = false;
          rejectDisabledMap[item.did] = false;
        }
      });
    }
  })
}
//上架下架
function toggleLockHandler(row) {
  // 根据当前行的status值来决定前端发送的status值
  const newStatus = row.status === 1 ? 0 : 1; // 切换状态
  const requestData = {
    did: row.did,
    status: newStatus // 使用新的状态值
  };
  request({
    url: '/dishes/status', // 您的服务器端点
    method: 'put', // 注意这里的方法是小写的'put'
    data: requestData, // 传递JSON格式的数据
  }).then(response => {
    if (response.data.code === 1) {
      ElMessage.success(response.data.message);
      // 假设row是通过did来唯一标识的，更新状态
      row.status = newStatus;
      // 刷新页面数据
      getDish(); // 调用数据加载函数
    } else {
      console.log(response)
      getDish(); // 调用数据加载函数
    }
  }).catch(error => {
    ElMessage.error('请求失败');
  });
}

//搜索
const searchFormRef=ref()
const searchFormModel=reactive({
  dname:'',
})
const searchOnSubmit=()=>{
  getDish()
}
const searchOnReset=()=>{
  searchFormModel.dname=''
}
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize.value=val;
  getDish();
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value=val;
  getDish()
}
//删除一条
const tableDeleteHandler = (rowIndex , rowData) => {
  ElMessageBox.confirm(
      '确认删除 : ' +rowData.dname,
      'Warning',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {//点击了删除按钮
    request({
      method:'delete',
      url:'/dishes/del/'+rowData.did
    }).then(req=>{
      if (200==req.data.errorCode){
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getDish()
      }
    })
  })
      .catch(() => {//点击了取消按钮
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
//增加
const formAddData = {
  dname:'',
  dtype:'',
  dphotourl:'',
  dprice:'',
  dfood:''
}
//...formAddData 解构 formAddData
const formAdd = reactive({...formAddData})
const formEditData = {
  did:'',
  dname:'',
  dprice:'',
  dtype:'',
  dphotourl: '',
  dfood: ''
}
// 编辑表单绑定数据模型
const formEdit = reactive({...formEditData});
const tableEditHandler = (rowIndex, rowData) => {
  console.log("-------------");
  console.log(rowIndex);
  console.log(rowData);

  formEdit.did = rowData.did; // 指定要编辑的记录的 ID
  formEdit.dname = rowData.dname;
  formEdit.dtype = rowData.dtype;
  formEdit.dphotourl = rowData.dphotourl;
  formEdit.dfood = rowData.dfood;
  formEdit.dprice = rowData.dprice; // 初始化编辑框的价格为当前价格

  dialogEditState.value = true; // 打开编辑模态框
};
const dialogEditState = ref(false)
// 编辑模态框的确认按钮点击事件处理函数
const dialogEditOnSubmit = () => {
  request({
    url: '/dishes/update',
    method: 'put',
    data: formEdit,
  }).then(req => {
    console.log(req);
    ElMessage({
      type: 'info',
      message: req.data.msg
    });
    if (200 == req.data.errorCode) {
      getDish();
    }
  });
  dialogEditState.value = false;
};

const dialogEditOnReset = () => {
  Object.assign(formEdit, formEditData);
  dialogEditState.value = false;
};

// 同意和拒绝按钮的禁用状态映射
const approveDisabledMap = reactive({});
const rejectDisabledMap = reactive({});
const statusClass = (isdel) => {
  switch (isdel) {
    case '未审核':
      return 'status-normal';
    case '已通过':
      return 'status-delayed';
    case '已拒绝':
      return 'status-cancelled';
    default:
      return '';
  }
};

const approveAudit = (row) => {
  // 模拟同意审核操作
  request({
    url:'/dishes/approve',
    method:'get',
    params:{
      did: row.did
    }
  }).then(req=>{
    if (req.data.errorCode==200){
      ElMessage.success("审核通过");
      row.isdel="已同意";
      getDish();
    }
  })
};

const rejectAudit = (row) => {
  // 模拟拒绝审核操作
  request({
    url:'/dishes/reject',
    method:'get',
    params:{
      did: row.did
    }
  }).then(req=>{
    if (req.data.errorCode==200){
      ElMessage.success("审核未通过");
      row.isdel="已拒绝";
      getDish();
    }
  })
};
</script>

<style scoped>
.el-breadcrumb{
  font-size: 18px;
  margin: 20px;
}
</style>